//
//  SAWarehousingDetailVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/5/24.
//

#import "SAWarehousingDetailVC.h"
#import "SAWarehousePurchaseInvoiceDetailAPI.h"
#import "SACommodityWarehousingSingleModel.h"
#import "SAWarehousingDetailCell.h"
#import "SASaleDocumentsHeaderView.h"
#import "SASalesOrderViewListModel.h"
#import "GFAlertView.h"
#import "SAWarehousePurchaseInvoiceRemoveAPI.h"
#import "SACloudPrintPushPrintMsgAPI.h"
#import "YBImageBrowser.h"

@interface SAWarehousingDetailVC ()<HTTPAPIDelegate, UITableViewDelegate, UITableViewDataSource,YBImageBrowserDataSource>

@property (nonatomic, strong) NSString *purchaseOrderId;
@property (nonatomic, strong) NSString *purchaseOrderNo;
@property (nonatomic, strong) UILabel *supplierLab;
@property (nonatomic, strong) UILabel *storeNameLab;
@property (nonatomic, strong) UILabel *moneyLab;
@property (nonatomic, strong) UILabel *dateLab;
@property (nonatomic, strong) UILabel *remarkLab;
@property (nonatomic, strong) SAWarehousePurchaseInvoiceDetailAPI *warehousePurchaseInvoiceDetailAPI;
@property (nonatomic, strong) SACommodityWarehousingSingleModel *singleModel;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SAWarehousePurchaseInvoiceRemoveAPI *warehousePurchaseInvoiceRemoveAPI;
@property (nonatomic, strong) UIButton *printBtn;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) int count;
@property (nonatomic, strong) SAOverallSetting *overallSetting;
@property (nonatomic, strong) SACloudPrintPushPrintMsgAPI *cloudPrintPushPrintMsgAPI;
@property (nonatomic, strong) UIView *grayView2;//标题头
@property (nonatomic, strong) NSArray *imageList;

@end

@implementation SAWarehousingDetailVC

-(instancetype)initWithPurchaseOrderId:(NSString *)purchaseOrderId AndPurchaseOrderNo:(NSString *)purchaseOrderNo {
    if (self = [super init]) {
        self.purchaseOrderId = purchaseOrderId;
        self.purchaseOrderNo = purchaseOrderNo;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.warehousePurchaseInvoiceDetailAPI == api) {
        self.singleModel = [SACommodityWarehousingSingleModel mj_objectWithKeyValues:data[@"data"]];
        if (self.singleModel.detailVO.providerName.length > 0) {
            if (self.singleModel.detailVO.providerMobile.length > 0) {
                self.supplierLab.text = [NSString stringWithFormat:@"%@(%@)",self.singleModel.detailVO.providerName,self.singleModel.detailVO.providerMobile];
            }else {
                self.supplierLab.text = self.singleModel.detailVO.providerName;
            }
            
            NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
            NSString *isSupplier = [NSString stringWithFormat:@"%@",menuList[7][@"isDelete"]];
            NSString *seeProvider = [NSString stringWithFormat:@"%@",menuList[7][@"perms"][@"seeProvider"]];
            if ([isSupplier isEqualToString:@"1"]) {
                self.supplierLab.text = @"******";
            }
            if ([seeProvider isEqualToString:@"1"]) {
                self.supplierLab.text = @"******";
            }
            
        }else {
            self.supplierLab.text = @"零散供货商";
        }
        self.storeNameLab.text = [NSString stringWithFormat:@"%@(%@)",self.singleModel.detailVO.empName,self.singleModel.detailVO.empMobile];
        self.moneyLab.text = [NSString stringWithFormat:@"%0.2f",[self.singleModel.detailVO.shouldPrice floatValue] / 100.f];
        self.dateLab.text = self.singleModel.detailVO.createDate;
        self.remarkLab.text = self.singleModel.detailVO.remark;
        [self.tableView reloadData];
        
        NSString *productViewCostPrice = [NSString stringWithFormat:@"%@",[SAValueManger shareInStance].userInfo.menuList[1][@"perms"][@"productViewCostPrice"]];
        if ([productViewCostPrice isEqualToString:@"1"]) {
            self.moneyLab.text = @"******";
        }
        
    }else if (self.warehousePurchaseInvoiceRemoveAPI == api) {
        !self.refreshBlock ?: self.refreshBlock();
        [self.navigationController popViewControllerAnimated:YES];
    }else if (self.cloudPrintPushPrintMsgAPI == api) {
        [Prompt popPromptViewWithMsg:@"正在进行共享打印" duration:2];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
   
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.singleModel.productInfoList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.singleModel.productInfoList[section].toPendSkuAttrs.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAWarehousingDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAWarehousingDetailCell" forIndexPath:indexPath];
    SASalesOrderToPendSkuList *model = self.singleModel.productInfoList[indexPath.section].toPendSkuAttrs[indexPath.row];
    cell.model = model;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(40);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SASaleDocumentsHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SASaleDocumentsHeaderView"];
    SAProductListModel *model = (SAProductListModel *)self.singleModel.productInfoList[section];
    header.model = model;
    WeakSelf
    header.imageBlock = ^{
        [weakSelf showImage:model.imgList];
    };
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(40);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(0.5);
}

-(void)clickedInvalidBtn {
    GFAlertView *alertView = [GFAlertView alertViewWithMsg:@"提示" detailMsg:@"确认作废该单据吗?" knowBtnBlock:^(UIButton *knowBtn) {
        [knowBtn addTarget:self action:@selector(clickedInvalid) forControlEvents:UIControlEventTouchUpInside];
    }];
    [alertView showWithAnimation];
}

-(void)clickedInvalid {
    self.warehousePurchaseInvoiceRemoveAPI.pendOrderId = self.singleModel.detailVO.pendOrderId;
    [self.warehousePurchaseInvoiceRemoveAPI sendRequestToServerWithActivityViewAndMask:POST];
}

//打印
-(void)clickedPrintBtn
{
    [self startTime];
    if (self.overallSetting.printerSetting.printerStatus == 2 && [SAValueManger shareInStance].printType == 1) {
        [SAPrintReceiptStorage printWithTotalData:self.singleModel printSuccessBlock:^{

        }];
    }else {
        if (kIsTestServer == 1) {
            self.cloudPrintPushPrintMsgAPI.merchantId = [SAValueManger shareInStance].userInfo.merchantId;
            self.cloudPrintPushPrintMsgAPI.type = @"3";
            self.cloudPrintPushPrintMsgAPI.data = self.purchaseOrderId;
            [self.cloudPrintPushPrintMsgAPI submitForm:POST];
        }else {
            [Prompt popPromptViewWithMsg:@"未连接打印机" duration:2];
        }
    }
}

-(void)startTime {
    self.printBtn.userInteractionEnabled = NO;
    [self.printBtn setTitle:@"打印" forState:UIControlStateNormal];
    self.count = 3;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
}

- (void)timerFired {
    if (self.count != 1) {
        self.count -= 1;
    } else {
        self.printBtn.userInteractionEnabled = YES;
        [self.printBtn setTitle:@"打印" forState:UIControlStateNormal];
        // 停掉定时器
        [self.timer invalidate];
        self.timer = nil;
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat y = scrollView.contentOffset.y;
    self.grayView2.hidden = y < kScaleNum(171);
}

-(void)showImage:(NSArray *)imageList {
    self.imageList = imageList;
    if (self.imageList.count > 0) {
        NSMutableArray *imageMarr = [NSMutableArray array];
        for (NSString *url in self.imageList) {
            NSString *newUrl = [url stringByReplacingOccurrencesOfString:@"?x-oss-process=style/thumbnail" withString:@""];
            NSString *imageUrl = [NSString stringWithFormat:@"%@?x-oss-process=image/resize,l_720",newUrl];
            [imageMarr addObject:imageUrl];
        }
        self.imageList = imageMarr;
        YBImageBrowser *browser = [YBImageBrowser new];
        browser.dataSourceArray = self.imageList;
        browser.dataSource = self;
        browser.currentPage = 0;
        [browser show];
    }else {
        [Prompt popPromptViewWithMsg:@"该商品没有图片" duration:2];
    }
}

//YBImageBrowserDataSource 代理实现赋值数据
- (NSInteger)yb_numberOfCellsInImageBrowser:(YBImageBrowser *)imageBrowser {
    return self.imageList.count;
}

- (id<YBIBDataProtocol>)yb_imageBrowser:(YBImageBrowser *)imageBrowser dataForCellAtIndex:(NSInteger)index {
    NSString *urlStr = [self.imageList objectAtIndex:index];
    YBIBImageData *data = [YBIBImageData new];
    data.imageURL = [NSURL URLWithString:urlStr];
    return data;
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:self.purchaseOrderNo];
    [self setBgImage:nil];
    
    UIView *headerView = [[UIView alloc] initWithFrame:SARectMake(0, 0, kBaseScreenWidth, 206)];
    headerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:headerView];
    
    NSArray *arr = @[@"实付金额", @"供货商", @"店员", @"日期", @"备注"];
    
    for (int i = 0; i < arr.count; i++) {
        UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        titleBtn.frame = CGRectMake(kScaleNum(20), kScaleNum(51 + 30 * (i - 1)), kScaleNum(70), kScaleNum(30));
        [titleBtn setTitle:arr[i] forState:UIControlStateNormal];
        [titleBtn setTitleColor:kLightgGrayColor forState:UIControlStateNormal];
        titleBtn.titleLabel.font = kFont(15);
        titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [headerView addSubview:titleBtn];
        
        UILabel *contentLab = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - kScaleNum(285), kScaleNum(51 + 30 * (i - 1)), kScaleNum(265), kScaleNum(30))];
        contentLab.font = kFont(15);
        contentLab.textAlignment = NSTextAlignmentRight;
        contentLab.textColor = kLightgGrayColor;
        [headerView addSubview:contentLab];
        
        if (i == 0) {
            self.moneyLab = contentLab;
            titleBtn.frame = CGRectMake(kScaleNum(20), 0, kScaleNum(100), kScaleNum(50));
            contentLab.frame = CGRectMake(kScreenWidth - kScaleNum(255), 0, kScaleNum(235), kScaleNum(50));
            titleBtn.titleLabel.font = kFont(18);
            contentLab.font = kFont(18);
            [titleBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
            contentLab.textColor = kBlackColor;
        }else if (i == 1) {
            self.supplierLab = contentLab;
        }else if (i == 2) {
            self.storeNameLab = contentLab;
        }else if (i == 3) {
            self.dateLab = contentLab;
        }else if (i == 4) {
            self.remarkLab = contentLab;
        }
        
        if (i == 0) {
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(kScaleNum(20), kScaleNum(50), kScreenWidth - kScaleNum(40), kScaleNum(1))];
            line.backgroundColor = kLineColor;
            [headerView addSubview:line];
        }
    }
    
    UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(171), kScreenWidth, kScaleNum(35))];
    grayView.backgroundColor = kColor(228, 231, 243, 1);
    [headerView addSubview:grayView];
    NSArray *arr2 = @[@"商品", @"数量", @"单价", @"小计"];
    for (int i = 0; i < arr2.count; i++) {
        UILabel *titleLab = [[UILabel alloc] init];
        titleLab.text = arr2[i];
        titleLab.font = kFont(15);
        titleLab.textColor = kLightgGrayColor;
        [grayView addSubview:titleLab];
        titleLab.textAlignment = NSTextAlignmentCenter;
        if (i == 0) {
            titleLab.frame = CGRectMake(kScaleNum(20), 0, kScaleNum(60), kScaleNum(35));
            titleLab.textAlignment = NSTextAlignmentLeft;
        }else if (i == 1) {
            titleLab.frame = CGRectMake(kScaleNum(150), 0, kScaleNum(70), kScaleNum(35));
        }else if (i == 2) {
            titleLab.frame = CGRectMake(kScaleNum(225), 0, kScaleNum(70), kScaleNum(35));
        }else if (i == 3) {
            titleLab.frame = CGRectMake(kScaleNum(300), 0, kScaleNum(70), kScaleNum(35));
        }
    }
    
    if ([self.stateType isEqualToString:@"1"]) {
        self.tableView.frame = CGRectMake(0, kScaleNum(StatusHeight), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight));
        UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pink_invalid"]];
        imageV.frame = CGRectMake(kScreenWidth - kScaleNum(90), kScaleNum(10), kScaleNum(80), kScaleNum(59));
        [headerView addSubview:imageV];
    }else {
        if([self.merchantId integerValue] == [SAValueManger shareInStance].userInfo.merchantId) {
            UIButton *invalidBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            invalidBtn.frame = CGRectMake(0, kScreenHeight - kScaleNum(35) - SafeFooterHeight, kScreenWidth/2, kScaleNum(35) + SafeFooterHeight);
            [invalidBtn setTitle:@"作废" forState:UIControlStateNormal];
            invalidBtn.backgroundColor = kColor(228, 231, 243, 1);
            invalidBtn.titleLabel.font = kBFont(18);
            [invalidBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [invalidBtn addTarget:self action:@selector(clickedInvalidBtn) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:invalidBtn];
            
            UIButton *printBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            printBtn.frame = CGRectMake(kScreenWidth/2, kScreenHeight - kScaleNum(35) - SafeFooterHeight, kScreenWidth/2, kScaleNum(35) + SafeFooterHeight);
            [printBtn setTitle:@"打印" forState:UIControlStateNormal];
            printBtn.titleLabel.font = kBFont(18);
            printBtn.backgroundColor = kPinkColor;
            [printBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [printBtn addTarget:self action:@selector(clickedPrintBtn) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:printBtn];
            self.printBtn = printBtn;
        }else {
            UIButton *printBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            printBtn.frame = CGRectMake(0, kScreenHeight - kScaleNum(35) - SafeFooterHeight, kScreenWidth, kScaleNum(35) + SafeFooterHeight);
            [printBtn setTitle:@"打印" forState:UIControlStateNormal];
            printBtn.titleLabel.font = kBFont(18);
            printBtn.backgroundColor = kPinkColor;
            [printBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [printBtn addTarget:self action:@selector(clickedPrintBtn) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:printBtn];
        }
    }
    
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = headerView;
    
    self.overallSetting = [SAOverallSetting shareInstance];
    
    self.warehousePurchaseInvoiceDetailAPI.purchaseOrderId = self.purchaseOrderId;
    [self.warehousePurchaseInvoiceDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
    
    UIView *grayView2 = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight)-0.5, kScreenWidth, kScaleNum(35))];
    grayView2.backgroundColor = kColor(228, 231, 243, 1);
    grayView2.hidden = YES;
    [self.view addSubview:grayView2];
    for (int i = 0; i < arr2.count; i++) {
        UILabel *titleLab = [[UILabel alloc] init];
        titleLab.text = arr2[i];
        titleLab.font = kFont(15);
        titleLab.textColor = kLightgGrayColor;
        [grayView2 addSubview:titleLab];
        titleLab.textAlignment = NSTextAlignmentCenter;
        if (i == 0) {
            titleLab.frame = CGRectMake(kScaleNum(20), 0, kScaleNum(60), kScaleNum(35));
            titleLab.textAlignment = NSTextAlignmentLeft;
        }else if (i == 1) {
            titleLab.frame = CGRectMake(kScaleNum(150), 0, kScaleNum(70), kScaleNum(35));
        }else if (i == 2) {
            titleLab.frame = CGRectMake(kScaleNum(225), 0, kScaleNum(70), kScaleNum(35));
        }else if (i == 3) {
            titleLab.frame = CGRectMake(kScaleNum(300), 0, kScaleNum(70), kScaleNum(35));
        }
    }
    self.grayView2 = grayView2;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 35) - SafeFooterHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SASaleDocumentsHeaderView class] forHeaderFooterViewReuseIdentifier:@"SASaleDocumentsHeaderView"];
        [_tableView registerClass:[SAWarehousingDetailCell class] forCellReuseIdentifier:@"SAWarehousingDetailCell"];
    }
    return _tableView;
}

-(SAWarehousePurchaseInvoiceDetailAPI *)warehousePurchaseInvoiceDetailAPI {
    if (!_warehousePurchaseInvoiceDetailAPI) {
        _warehousePurchaseInvoiceDetailAPI = [SAWarehousePurchaseInvoiceDetailAPI apiWithDelegate:self];
    }
    return _warehousePurchaseInvoiceDetailAPI;
}

-(SAWarehousePurchaseInvoiceRemoveAPI *)warehousePurchaseInvoiceRemoveAPI {
    if (!_warehousePurchaseInvoiceRemoveAPI) {
        _warehousePurchaseInvoiceRemoveAPI = [SAWarehousePurchaseInvoiceRemoveAPI apiWithDelegate:self];
    }
    return _warehousePurchaseInvoiceRemoveAPI;
}

-(SACloudPrintPushPrintMsgAPI *)cloudPrintPushPrintMsgAPI {
    if (!_cloudPrintPushPrintMsgAPI) {
        _cloudPrintPushPrintMsgAPI = [SACloudPrintPushPrintMsgAPI apiWithDelegate:self];
    }
    return _cloudPrintPushPrintMsgAPI;
}

@end
